// all the contract related methods will be here
import { JsonqlValidationError } from 'jsonql-errors'

import { timestamp, isContract, ENDPOINT_TABLE } from '../utils'
import { localStore } from '../stores'

import HttpClass from './http-cls';

// export
export default class ContractClass extends HttpClass {

  constructor(opts) {
    super(opts)
  }

  /**
   * return the contract public api
   * @return {object} contract
   */
  getContract() {
    const contracts = this.readContract()
    this.log('getContract first call', contracts)
    if (contracts && Array.isArray(contracts)) {
      const contract = contracts[ this[ENDPOINT_TABLE + 'Index'] || 0 ]
      if (contract) {
        return Promise.resolve(contract)
      }
    }
    return this.get()
      .then( this.storeContract.bind(this) )
  }

  /**
   * We are changing the way how to auth to get the contract.json
   * Instead of in the url, we will be putting that key value in the header
   * @return {object} header
   */
  get contractHeader() {
    let base = {};
    if (this.opts.contractKey !== false) {
      base[this.opts.contractKeyName] = this.opts.contractKey;
    }
    return base;
  }

  /**
   * Save the contract to local store
   * @param {object} contract to save
   * @return {object|boolean} false when its not a contract or contract on OK
   */
  storeContract(contract) {
    // first need to check if the contract is a contract
    if (!isContract(contract)) {
      throw new JsonqlValidationError(`Contract is malformed!`)
      //return false;
    }
    let args = [contract]
    if (this.opts.contractExpired) {
      let expired = parseFloat(this.opts.contractExpired)
      if (!isNaN(expired) && expired > 0) {
        args.push(expired)
      }
    }
    // calling the setter
    this.jsonqlContract = args;
    // return it
    this.log('storeContract return result', contract)
    return contract;
  }

  /**
   * return the contract from options or localStore
   * @return {object} contract
   */
  readContract() {
    let contract = isContract(this.opts.contract)
    return contract ? this.opts.contract : localStore.get(this.opts.storageKey)
  }
}
